-- UISkyCityCombatResult
-- Create by chendh Jan/19/2016
-- 天空之城战斗结果界面

-- UISkyCityCombatResult继承自Layer
UISkyCityCombatResult = class("UISkyCityCombatResult", function()
    return cc.Layer:create();
end);

function UISkyCityCombatResult.create(result, bonus, callback, args)
    -- 胜利失败播放不同背景，结果不明那就算了。
    if result == 1 then
        AudioM.playBgMusic("victory_battle");
    elseif result == 0 then
        AudioM.playBgMusic("failure_battle");
    end

    return UISkyCityCombatResult.new(result, bonus, callback, args);
end

-- 构造函数
function UISkyCityCombatResult:ctor(result, bonus, callback, args)
    -- 初始化
    self:setName("UISkyCityCombatResult");
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.result = result;
    self.info = bonus or {};
    self.callback = callback;
    self.args = args;

    -- 如果是一层数组，那么转成2层数组
    if bonus and type(bonus[1]) == "number" then
        self.info = { bonus, };
    end

    local node = cc.CSLoader:createNode("layout/sky_city/SkyCityCombatResult.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    self.CT = CT;

    -- 初始化view
    self:initView();
    self:redraw();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    self:resize();

    -- 注册任意地方点击返回事件
    local bgImage = findChildByName(self.node, "bg/bgImg");
    local function onBgBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if not self.isEnd then
                self.isEnd = true;

                local textNode = findChildByName(self.CT, "title");
                self:stopAllActions();
                textNode:stopAllActions();

                local num = #self.labelList;
                for i = 1, num do
                    local label = self.labelList[i];
                    label:stopAllActions();
                end

                self:resetPosition();
                self:redraw();
            else
                if self.callback then
                    self.callback();
                end
                UIMgr.getCurrentScene():removeFormByName("UISkyCityCombatResult");

                -- 战斗结算后主界面不明，以是否开启着天空之城界面为判断
                if UIMgr.getCurrentScene():isOpen("UISkyCity") then
                    AudioM.playBgMusic("bgm_sky");
                else
                    AudioM.playBgMusic("bgm_camp");
                end
            end
        end
    end

    bgImage:addTouchEventListener(onBgBackClick);
end

-- 重置界面各元素坐标
function UISkyCityCombatResult:resetPosition()
    local num = #self.labelList;
    for i = 1, num do
        local label = self.labelList[i];
        label:setOpacity(255);
        label:setScale(1);
        label:setVisible(true);
        label:setPosition(label.initPosition);
        label:stopAllActions();
    end

    local textNode = findChildByName(self.CT, "title");
    textNode:stopAllActions();
end

-- 重绘
function UISkyCityCombatResult:redraw()
    closeCommunicatingForm();
end

-- 初始化视图
function UISkyCityCombatResult:initView()
    -- 绘制标题
    local title = findChildByName(self.CT, "title");

    -- 奖励内容描述
    local arr = self.info;
    self.labelList = {};
    local kerning = 0;
    if not isChineseLang() then
        kerning = -1;
    end
    local bonusListNode = findChildByName(self.CT, "bonus");
    local initX = bonusListNode:getPositionX();
    local initY = bonusListNode:getPositionY();
    for index, value in pairs(arr) do
        local text = ccui.Text:create();
        TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BRIGHT_YELLOW, false, kerning);
        text:setTag(index);
        text:setFontName(getLocFontName());

        -- 文本居中
        text:setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);

        text:setPosition(0, -40 * index);
        text:setVisible(false);
        text.initPosition = cc.p(text:getPositionX(), text:getPositionY());
        bonusListNode:addChild(text);

        local name;
        local desc;
        if value[1] == 1 then
            name = ItemM.query(value[2], "name");
        elseif value[1] == 2 then
            name = FieldsM.getFieldName(value[2]);
        elseif value[1] == 6 then
            name = SkyShipSkillM.query(value[2], "name");
        elseif value[1] == 8 then
            name = SkyRobotM.query(value[2], "name");
        end

        if self.args and self.args["video"] then
            -- 录像的话，那就是被掠夺，显示为-
            desc = name .. " - " .. value[3];
        else
            desc = name .. " + " .. value[3];
        end

        text:setString(desc);

        table.insert(self.labelList, text);
    end

    self:playEffect();
end

-- 注册事件处理回调函数
function UISkyCityCombatResult:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UISkyCityCombatResult 界面析构清理");
            self:showBonusNotify();
        elseif ev == "enter" then

        end
    end);
end

-- 震动
function UISkyCityCombatResult:shake()
    local duration = 0.03;
    local offset = 6;

    local uiForm = UIMgr.getCurrentScene():getFormByName("UISkyCityCombatResult");
    if uiForm then
        local moveLeft = cc.MoveBy:create(duration, cc.p(-offset, 0));
        local moveDown = cc.MoveBy:create(duration, cc.p(0, -offset));
        local moveRight = cc.MoveBy:create(duration, cc.p(offset, 0));
        local moveUp = cc.MoveBy:create(duration, cc.p(0, offset));
        local action = cc.Sequence:create(moveLeft, moveDown, moveRight, moveUp);
        uiForm:runAction(cc.Repeat:create(action, 1));
        self:runAction(action:clone());
    end
end

-- 播放特效
function UISkyCityCombatResult:playEffect()
    local titleNode = findChildByName(self.CT, "title");

    local function setActionEnd()
        self.isEnd = true;
    end

    AudioM.playFx("new_level");
    -- 文字弹出
    local function playTextEffect()
        -- 奖励描述
        local num = #self.labelList;
        for i = 1, num do
            local label = self.labelList[i];
            label:setPositionX(label:getPositionX() + AlignM.frameSize.width / 2 + 100);
            local delay = cc.DelayTime:create(i * 0.2);
            local move1 = cc.EaseIn:create(cc.MoveBy:create(0.3, cc.p(AlignM.frameSize.width / -2 - 110, 0)), 5);
            local move2 = cc.MoveBy:create(0.1, cc.p(10, 0));
            local callFunc = cc.CallFunc:create(function()
                label:setVisible(true);
                label:setOpacity(0);
            end);

            label:runAction(cc.Sequence:create(delay, callFunc, cc.Spawn:create(cc.FadeIn:create(0.3), move1), move2));
        end

        performWithDelay(self, setActionEnd, (num + 1) * 0.2);
    end

    -- 标题飞入
    local str;
    local textMask;
    if self.result == 1 then
        str = getLocStr("sky_city_combat_win");
        textMask = "images/ui/text_mask/text_mask.png";
    else
        str = getLocStr("sky_city_combat_lose");
        textMask = "images/ui/text_mask/text_mask6.png";
    end

    local len = string.getWCharCount(str);
    local fontSize = 80 * getLocFontSizeMulti();

    -- 标题飞入
    local function playFlyInEffect()
        titleNode:setString(str);
        -- 生成艺术字并旋转飞入
        genArtWordAndRotateFlyIn(titleNode, fontSize, textMask);
        performWithDelay(titleNode, playTextEffect, 0.8);
    end

    playFlyInEffect();

    -- 播放光效
    local effectNode = findChildByName(self.node, "CT/effect");

    -- 礼炮特效
    local function palySalvoEffect()
        effectNode:removeAllChildren();
        playEffect(effectNode, 1718);

        performWithDelay(effectNode, palySalvoEffect, 1.5);
    end

    local function frameEventFunc(frame)
        if frame.getEvent and frame:getEvent() == "pilor" then
            local name = frame:getNode():getName();
            local index = frame:getFrameIndex();

            if self.result == 1 then
                if index == 79 then
                    effectNode:removeAllChildren();

                    -- 播放礼炮特效
                    palySalvoEffect();
                end
            else
                if index == 38 then
                    for i = 1, 5 do
                        local slimeNode = findChildByName(self.node, "CT/slime" .. i);
                        local effectList = { 1708, 1707, 1706, 1706, 1707, };
                        local _, effect = playEffect(slimeNode, effectList[i]);

                        if i >= 3 then
                            effect:setScaleX(-1 * effect:getScaleX());
                        end

                        local initScale = slimeNode:getScale();
                        local delay = cc.DelayTime:create(i / 10);
                        local scaleTo = cc.ScaleTo:create(0.3, initScale);
                        local fadeIn = cc.FadeIn:create(0.3);
                        slimeNode:setAnchorPoint(cc.p(0.5, 0));
                        slimeNode:setScale(0.1);
                        slimeNode:setOpacity(0);
                        slimeNode:runAction(cc.Sequence:create(delay, cc.Spawn:create(fadeIn, scaleTo)));
                    end

                    local windNode = findChildByName(self.node, "CT/wind");

                    local function play()
                        playEffect(windNode, 2034, 0, 0);
                        playEffect(windNode, 2035, 0, 0);

                        performWithDelay(windNode, play, math.random(3, 8));
                    end

                    play();
                end
            end
        end
    end

    if self.result == 1 then
        playEffect(effectNode, 1717, nil, nil, frameEventFunc);
    else
        playEffect(effectNode, 1705, nil, nil, frameEventFunc);
    end
end

function UISkyCityCombatResult:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    local bg = findChildByName(self.node, "bg");
    bg:setScaleX(bg:getScaleX() * 1.1);
    bg:setScaleY(bg:getScaleY() * 1.1);

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");
end

function UISkyCityCombatResult:showBonusNotify()
    if self.result ~= 1 then
        return;
    end

    if not self.args["isSkytower"] then
        return;
    end

    if #self.info < 1 then
        return;
    end

    local camp = ME.user.dbase:query("activedSkyGroup");

    local shortName = CampM.query(camp, "short_name");
    local towerName = CampM.query(camp, "sky_tower_name");

    local title = string.format(getLocStr("tower_title"), shortName);

    local floor = SkyTowerM.getProgress(camp);

    local msg = string.format(getLocStr("pass_skytower_floor"), towerName, floor);

    showBonusNotifyForm(title, self.info, nil, msg);
end